/*
 *   Licensed to the Apache Software Foundation (ASF) under one
 *   or more contributor license agreements.  See the NOTICE file
 *   distributed with this work for additional information
 *   regarding copyright ownership.  The ASF licenses this file
 *   to you under the Apache License, Version 2.0 (the
 *   "License"); you may not use this file except in compliance
 *   with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing,
 *   software distributed under the License is distributed on an
 *   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *   KIND, either express or implied.  See the License for the
 *   specific language governing permissions and limitations
 *   under the License.
 *
 */
package com.bkbw.live.battle.net.codec;

import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import com.bkbw.live.battle.net.message.MessageObject;
import com.bkbw.live.common.GameConfig;

import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.example.imagine.step1.ImageResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * a decoder for {@link ImageResponse} objects 
 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
 */

public class NetResponseDecoder extends CumulativeProtocolDecoder {
	Logger logger = LoggerFactory.getLogger(GameConfig.LoggerName);
    protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    	//System.out.println("mina decode");
    	//logger.debug("mina decode");
    	
    			// try to read second image
    	// TODO
    	// here may cause error if tcp data is very long
	       // if (in.prefixedDataAvailable(4,16000)) {
    	try {
    	 if (in.prefixedDataAvailable(4,200000)) {
	        	//先读取4个字节作为长度
	        	int len = in.getInt();
	        	//System.out.println("mina read "+len);
	        	//logger.debug("mina read "+len);
	        	//然后读取2个字节作为消息头
	        	short head = in.getShort();
	        	//System.out.println("收到消息"+head);
	        	//根据长度来创建字节数组
		    	byte[] bytes = new byte[len-2];
		    	//读取二进制数据
		    in.get(bytes);
		    //..根据不同的消息头来进行反序列化,这里使用了Java的反射机制
		    Class c = Class.forName(PackageHead.getClassNameByHead(head));
		    //long n1 = System.nanoTime();
		    java.lang.reflect.Method m = c.getMethod("parseFrom", byte[].class);
		    Object tt = m.invoke(null,bytes);
		    //long n2 = System.nanoTime();
		    //logger.debug("proto parse " + c.getName() + " use time " + (n2 - n1) * 0.000000001);
		    //把proto对象和消息头合并为MessageObject往下传递
		    MessageObject mo = new MessageObject(head,tt,session);
	        out.write(mo);
            return true;
        } else {
            // not enough data available to read second image
        	//System.out.println("may be weapon");
            return false;
        }
//      	for(int i=0;i<10;i++){
//      		byte b = in.get();
//      		System.out.print(b+",");
//      	}
//    		
//    		return true;
    	}
    	catch (Exception e){
    		
    		
    		e.printStackTrace();
    		throw new Exception(e);
    	}
    }
    	
    
}
